<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

if(!$USER->isLoggedIn()){
    JFX::addError($this->Lang('must_be_logged_in'));
    JFX::setLastPage();
    JFX::redirect($Antz->getUrlById($this->GetConfig('login_id')));
};

$showFields = explode(',', $this->GetConfig('profile_show_fields'));

if(Antz_IntelliForm::submitted('profile')){

    $emailVerification = (bool) $this->GetConfig('email_verification');
    $hashOrig = rand();
    $hash = md5($hashOrig);

    // we have a valid user id
    $username = post('username');
    $newPassword = post('newPassword');
    $password = post('password');
    $email = strtolower(post('email'));
    $emailMD5 = md5(strtolower($email));
    $fName = post('first_name');
    $lName = post('last_name');
    $dob = post('dob');
    $sex = post('sex');
    $subscriber = (int) post('subscriber');
    $country = preg_replace('/[^a-zA-Z0-9]/', '', post('country'));
    $city = (int) post('city');
    $address = post('address');
    
    

    $error = false;
    $uData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}iusers WHERE id = '{$USER->userid}'");

    if($email != $CRYPT->decrypt($uData['email_crypt']))
        $changingEmail = true;
    else
        $changingEmail = false;

    
    // username
    if($username != $uData['username']){
        $safeUsername = preg_replace('/[^a-zA-Z0-9\-_]/', '', $username);
        if(trim($username)==''){
            $error = true;
            JFX::addFormError('username', $this->Lang('cannot_be_blank'));
        }elseif($username != $safeUsername){
            $error = true;
            JFX::addFormError('username', $this->Lang('invalid_characters'));
        }else{
            if($DB->countRows($CONFIG->dbprefix.'iusers', "username = '{$safeUsername}'")>0){
                $error = true;
                JFX::addFormError('username', $this->Lang('already_registered'));
            };
        };
    };


    if(!JFX_Filter::checkEmail($email)){
        $error = true;
        JFX::addFormError('email', 'Invalid email');
    };
    if($changingEmail && $DB->countRows($CONFIG->dbprefix.'iusers', "email_md5 = '{$emailMD5}'")>0){
    	   $error = true;
        JFX::addFormError('email', $this->Lang('already_registered'));
    };
    if($changingEmail && $DB->countRows($CONFIG->dbprefix.'iusers', "new_email = '{$email}'")>0){
        $error = true;
        JFX::addFormError('email', $this->Lang('already_registered'));
    };
    if($newPassword!='' && $CRYPT->decrypt($uData['pass'])!=$password){
        $error = true;
        JFX::addFormError('password', $this->Lang('incorrect_password'));
    }else if($newPassword != '' && (strlen($newPassword)<6 || strlen($newPassword)>20)){
        $error = true;
        JFX::addFormError('newPassword', $this->Lang('6-20_chars'));
    };

    if($subscriber != 0){
        $subscriber = 1;
    };
    
    // Name
    $fName = substr($fName, 0, 24);
    $lName = substr($lName, 0, 24);
    if(in_array('first_name', $showFields)){
	    if($this->GetConfig('fe_insist_fname') && trim($fName) == ''){
    	    $error = true;
        	JFX::addFormError('first_name');
	    }else{
    	    if(strlen($fName)>12){
        	    $error = true;
            	JFX::addFormError('first_name', $this->Lang('max_12_chars'));
        	};
	    };
    };

    if(in_array('last_name', $showFields)){
	    if($this->GetConfig('fe_insist_fname') && trim($lName) == ''){
	        $error = true;
	        JFX::addFormError('last_name');
	    }else{
	        if(strlen($lName)>12){
	            $error = true;
	            JFX::addFormError('last_name', $this->Lang('max_12_chars'));
	        };
	    };
    };

    // country and city
    if(in_array('country', $showFields)){
	    if($this->GetConfig('fe_country_required') == 1 && ($country == '' || $DB->countRows($CONFIG->dbprefix.'iusers_countries', "id = '{$country}'")==0)){
	        $error = true;
	        JFX::addFormError('country');
	    };
    };
	  if(in_array('city', $showFields)){
	    if($this->GetConfig('fe_city_required') == 1 && ($city == 0 || $DB->countRows($CONFIG->dbprefix.'iusers_cities', "id = '{$city}'")==0)){
	        $error = true;
	        JFX::addFormError('city');
	    };
	};
	if(in_array('sex', $showFields)){
	    // terms and coditions
	    if($sex != 'm' && $sex != 'f' && $sex != '0'){
	        $error = true;
	        JFX::addFormError('sex');
	    }
	};  
    
    

    // to other modules
	$hookParams = array(
		'error' => false,
		'errors' => array(),
		'user_data' => $uData
	);
	JFX::hook('JFX_Module_Iusers.profileCheck', $hookParams);
	if($hookParams['error']){
		$error = true;
		if(count($hookParams['errors'])>0){
			foreach($hookParams['errors'] as $errorMsg){
				JFX::addError($errorMsg);
			};
		};
	};

    if(!$error){
        // safe to process

        if($this->GetConfig('secure_login')==1){
            $loginUrl = str_replace('http://', 'https://', JFX::getUrlById($loginUrl));
        }else{
            $loginUrl = JFX::getUrlById($loginUrl);
        };

        if($newPassword != '') $uData['pass'] = $CRYPT->crypt($newPassword);
        $uData['username'] = $username;
        $uData['first_name'] = $fName;
        $uData['last_name'] = $lName;
        $uData['dob'] = $dob;
        $uData['sex'] = $sex;
        $uData['country'] = $country;
        $uData['city'] = $city;
        $uData['address'] = $address;
        $uData['email_subscriber'] = $subscriber;

        if($changingEmail && $this->GetConfig('email_verification')){
            $hashOrig = rand(0, 99).rand(0, 99);
            $hash = md5($hashOrig);
            $uData['new_email'] = $email;
            $uData['new_email_hash'] = $hash;

            // send email confirmation
            $sitename = $LANG->get('core', 'site_title');
            $subject = 'Your email has been changed';
            if($emailVerification) $emailTemplate = 'admin.manage.email_changed.verify.php';
            else $emailTemplate = 'admin.manage.email_changed.noverify.php';
            $emailParams = array(
                'new_email' => $email,
                'login_url' => $loginUrl,
                'name' => $fName.' '.$lName,
                'email' => $email,
                'username' => $uData['username'],
                'password' => $CRYPT->decrypt($uData['pass']),
                'sitename' => $sitename,
                'email_verification_url' => JFX::addParamsToUrl(JFX::getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
                'email_verification_url_htmlentities' => JFX::addParamsToUrl(JFX::getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true)
            );
            $msg = $this->ProcessEmailTemplate($emailTemplate, $emailParams);
            $toFrom = array(
                'toName' => $fName.' '.$lName,
                'toEmail' => $email
            );
            JFX_Email::sendRaw($subject, $msg, $toFrom, true);
            JFX::addSuccess($this->Lang('activation_required_email', $email));
        }else{
            // no email verification
            $uData['email_crypt'] = $CRYPT->crypt($email);
            $uData['email_md5'] = md5(strtolower($email));
            $uData['new_email'] = '';
            $uData['new_email_hash'] = '';
            JFX::addSuccess($this->Lang('details_updated'));
        };

        $DB->update($CONFIG->dbprefix.'iusers', $uData, "id = '{$uData['id']}'");

        // event
        $uData['password'] = $CRYPT->decrypt($uData['pass']);
        $uData['email'] = $CRYPT->decrypt($uData['email_crypt']);
        $hookParams = array('user_data' => $uData);
		JFX::hook('JFX_Module_Iusers.profileProcess', $hookParams);
    
        JFX::goLastPage();


    };// end if no error


};// end if submitted

$uData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}iusers WHERE id = '{$USER->userid}'");
$countries = $DB->fetchAll("SELECT * FROM ".$CONFIG->dbprefix.'iusers_countries ORDER BY title ASC');
if(trim($uData['country'])=='') $uData['country'] = $this->GetConfig('default_country');
$cities = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}iusers_cities WHERE country_id = '{$uData['country']}' ORDER BY title ASC");

$countryOptions = array();
foreach($countries as $k=>$v){
	$countryOptions[$v['id']] = $v['title'];
}
$cityOptions = array();
foreach($cities as $k=>$v){
	$cityOptions[$v['id']] = $v['title'];
}


$formFields = array(
	array(
		'name' => 'password',
		'value' => post('password'),
		'type' => 'password',
		'label' => $this->Lang('existing_password')
	),
	array(
		'name' => 'newPassword',
		'value' => post('newPassword'),
		'type' => 'password',
		'label' => $this->Lang('new_password')
	),
	array(
		'name' => 'email',
		'value' => post('email', $CRYPT->decrypt($uData['email_crypt'])),
		'type' => 'text',
		'label' => $this->Lang('email')
	)
);

if(in_array('username', $showFields)){
    $formFields[] = 
    array(
        'name' => 'username',
        'type' => 'text',
        'value' => post('username', $uData['username']),
        'label' => $this->Lang('username'),
        'required' => true
    );
}

if(in_array('first_name', $showFields)){
	$formFields[] =
	array(
		'name' => 'first_name',
		'value' => post('first_name', $uData['first_name']),
		'type' => 'text',
		'label' => $this->Lang('first_name'),
		'required' => (bool) $this->GetConfig('fe_insist_fname')
	);
};
if(in_array('last_name', $showFields)){
	$formFields[] =
	array(
		'name' => 'last_name',
		'value' => post('last_name', $uData['last_name']),
		'type' => 'text',
		'label' => $this->Lang('last_name'),
		'required' => (bool) $this->GetConfig('fe_insist_lname')
	);
};
if(in_array('dob', $showFields)){
	$formFields[] =
	array(
		'name' => 'dob',
		'value' => post('dob', $uData['dob']),
		'type' => 'text',
		'label' => $this->Lang('dob')
	);
};
if(in_array('sex', $showFields)){
	$formFields[] =
	array(
		'name' => 'sex',
		'value' => post('sex', $uData['sex']),
		'type' => 'select',
		'label' => $this->Lang('sex'),
		'options' => array(
			'0' => $this->Lang('both'),
			'm' => $this->Lang('male'),
			'f' => $this->Lang('female')
		)
	);
};
if(in_array('country', $showFields)){
	$formFields[] =
	array(
		'name' => 'country',
		'value' => post('country', $uData['country']),
		'type' => 'select',
		'label' => $this->Lang('country'),
		'options' => $countryOptions,
		'id' => 'countrySel',
		'extra' => array(
				0 => array(
				'command' => 'addJsEvent',
				'params' => array(
					"'onchange'",
					"'IUsers_Places.getCitiesForCountry(\'{$CONFIG->baseUrl}\', this, \'citySel\')'"
				)
			)
		),
		'required' => (bool) $this->GetConfig('fe_country_required')
	);
};
if(in_array('city', $showFields)){
	$formFields[] =
	array(
		'name' => 'city',
		'value' => post('city', $uData['city']),
		'type' => 'select',
		'label' => $this->Lang('city'),
		'options' => $cityOptions,
		'id' => 'citySel',
		'required' => (bool) $this->GetConfig('fe_city_required')
	);
};
if(in_array('address', $showFields)){
	$formFields[] =
	array(
		'name' => 'address',
		'value' => post('address', $uData['address']),
		'type' => 'textarea',
		'label' => $this->Lang('address')
	);
};

// implement the hook to get extra form fields from other modules
$hookParams = array('form_fields' => $formFields);
JFX::hook('JFX_Module_Iusers.profileForm', $hookParams);
$formFields = $hookParams['form_fields'];


// ready to create our form

if($this->GetConfig('auto_forms')){

	// prepare the structure for auto form generation
	$blocks = array(
		0 => array(
			'type' => 'full',
			'fieldsets' => array(
				0 => array(
					'legend' => $this->Lang('profile_legend'),
					'side' => 'left',
					'fields' => $formFields
				)
			)
		)
	);

	$form = JFX::makeForm($blocks, 'profile');

	$form->addSubmit($this->Lang('update'));

	echo $form->render();

}else{
	// assigning form components to smarty variables and processing template
	if($this->GetConfig('wrap_form_components')) $wrap = true;
	else $wrap = false;
	if($this->GetConfig('show_labels')) $labels = true;
	else $labels = false;

	foreach($formFields as $field){
		$component = JFX::makeFormComponent($field, $wrap, $labels);
		$SMARTY->assign('fc_'.$field['name'], $component->render());
	};

	$SMARTY->assign('profile_intelliform_seed', Antz_IntelliForm::seed('profile'));

	echo $this->ProcessTemplate('profile.tpl');

}

/* old way before Antz::hook implementation
$form = Antz::newObject('Antz_Form', __FILE__);
$block = $form->add('full');
$fs = $block->add($this->Lang('user_details'));
$pwd = $fs->addInput('password', 'password', $this->Lang('existing_password'), '')->required(true);
$pwd->addParameter('autocomplete', 'off');
$nPwd = $fs->addInput('password', 'newPassword', $this->Lang('new_password'), '');
$nPwd->addParameter('autocomplete', 'off');
$e = $fs->addInput('text', 'email', $this->Lang('email'), $CRYPT->decrypt($uData['email_crypt']));
$e->addParameter('autocomplete', 'off');
$fs->addInput('text', 'fName', $this->Lang('first_name'), $uData['first_name']);
$fs->addInput('text', 'lName', $this->Lang('last_name'), $uData['last_name']);
$fs->addInput('text', 'dob', $this->Lang('dob'), $uData['dob']);
$sex = $fs->addSelect('sex', $this->Lang('sex'), $uData['sex']);
$sex->add($this->Lang('both'), '0');
$sex->add($this->Lang('male'), 'm');
$sex->add($this->Lang('female'), 'f');
if($ELetters = $this->GetModuleInstance('ELetters')){
    $chk = $fs->addCheckboxGroup('chk');
    $chk->add('subscriber', $this->Lang('subscribe_to_newsletters'), '1', (bool) $uData['email_subscriber']);
};
$ctrySel = $fs->addSelect('country', $this->Lang('country'), post('country', $uData['country']));
$ctrySel->add($this->Lang('please_select'), '0');
//var_dump($countries);exit;
foreach($countries as $k=>$v){
    $ctrySel->add($v['title'], $v['id']);
};
$citySel = $fs->addSelect('city', $this->Lang('city'), post('city', $uData['city']));
$citySel->add($this->Lang('please_select'), '0');
foreach($cities as $k=>$v){
    $citySel->add($v['title'], $v['id']);
};
$ctrySel->addJsEvent('onchange', 'IUsers_Places.getCitiesForCountry(\''.$this->config['root_url'].'\', this, \''.$citySel->getId().'\')');

$fs->addInput('textarea', 'mg_editAddress', $this->Lang('address'), $uData['address']);

$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('update'));
*/



